<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <title>消息</title>
    <head th:insert="~{import :: head}">

    </head>

<body>
<div class="index-body">
    <script>
        $(document).ready(function() {
            // 仅当URL格式为 /messages/数字 时加载消息
            if (/\/messages\/\d+/.test(window.location.pathname)) {
                loadMessages();
            }
            // 发送消息逻辑
            $('#message-form').on('submit', function(e) {
                e.preventDefault();
                const content = $('#message-content').val().trim();
                if (!content) {
                    alert('消息内容不能为空');
                    return;
                }

                const sessionId = window.location.pathname.split('/').pop();

                $.post('/messages/send', {
                    sessionId: sessionId,
                    content: content
                }).done(function(response) {
                    $('#message-content').val('');
                    loadMessages();
                    $(document).trigger('message:sent');
                });
            });

            // 仅本页使用的轮询
            setInterval(loadMessages, 5000);
        });

        function loadMessages() {
            const sessionId = window.location.pathname.split('/').pop();
            if (!sessionId) return;


            $.get(`/messages/${sessionId}/content`, function(messages) {
                let html = '';
                const currentUserId = parseInt($('#current-user-id').val()) || 0;
                // 从隐藏字段获取当前用户ID并转为数字类型
                messages.forEach(msg => {
                    // 确保比较双方都是数字类型
                    const isCurrentUser = parseInt(msg.senderId) === currentUserId;
                    const sender = msg.sender || {};

                    if (isCurrentUser) {
                        // 当前用户发送的消息 - 靠右显示
                        html += `
                <div class="message-item d-flex justify-content-end mb-3">
                    <div class="message-bubble bg-primary text-white p-3 rounded">
                        ${msg.content}
                    </div>
                </div>`;
                    } else {
                        // 对方发送的消息 - 靠左显示并带头像
                        html += `
                <div class="message-item d-flex align-items-start mb-3">
                    <img src="${sender.avatarUrl || '/default-avatar.png'}"
                         class="rounded-circle mr-2" width="40" height="40"
                         alt="${sender.nickname || '用户'}">
                    <div class="message-bubble bg-light p-3 rounded">
                        <div class="font-weight-bold small">${sender.nickname || '未知用户'}</div>
                        ${msg.content}
                    </div>
                </div>`;
                    }
                });

                $('#message-list').html(html || '<div class="text-muted text-center py-3">没有消息</div>');
                $('#message-list').scrollTop($('#message-list')[0].scrollHeight);
            });
        }

        function updateUnreadCount() {
            $.get('/messages/unread-count', function(data) {
                if (data.code === "2000" && data.data > 0) {
                    $('#message-badge').text(data.data).show();
                } else {
                    $('#message-badge').hide();
                }
            });
        }
    </script>
    <div class="fixed-top" th:insert="~{navigation :: nav}"></div>

    <div class="container-fluid mt-5 pt-3">
        <div class="row">
            <!-- 左侧会话列表 -->
            <div class="col-lg-3 col-md-4">
                <div class="list-group">
                    <a th:each="messageSession : ${sessions}"
                       th:href="@{/messages/{id}(id=${messageSession.id})}"
                       class="list-group-item list-group-item-action">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <img th:src="${messageSession.otherUser.avatarUrl}"
                                     class="rounded-circle mr-2" width="40" height="40">
                                <span th:text="${messageSession.otherUser.nickname}"></span>
                            </div>
                            <span th:if="${messageSession.unreadCount > 0}"
                                  class="badge badge-primary rounded-pill"
                                  th:text="${messageSession.unreadCount}"></span>
                        </div>
                    </a>
                </div>
            </div>

            <!-- 右侧消息区域 -->
            <div class="col-lg-9 col-md-8">
                <input type="hidden" id="current-user-id" th:value="${session.user.id}">
                <div class="card">
                    <div class="card-header" th:text="${sessionId != null ? '消息详情' : '选择会话'}"></div>
                    <div class="card-body message-container" id="message-list">
                        <!-- 无会话时的提示 -->
                        <div th:if="${sessionId == null}" class="text-center text-muted py-5">
                            请从左侧选择一个会话
                        </div>
                        <div th:fragment="message-list">
                            <div th:each="message : ${messages}" class="message-item">
                                <!-- 消息内容渲染 -->
                                <div th:text="${message.content}"></div>
                            </div>
                        </div>
                        <div th:if="${sessionId != null}" th:fragment="empty1">
                            没有消息
                        </div>

                    </div>
                    <!-- 仅当有会话时显示发送框 -->
                    <div class="card-footer" th:if="${sessionId != null}">
                        <form id="message-form">
                            <div class="input-group">
                                <input type="text" class="form-control"
                                       placeholder="输入消息..."
                                       id="message-content"
                                       required>
                                <div class="input-group-append">
                                    <button class="btn btn-primary" type="submit">发送</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>